package site.teamo.biu.net.common.web.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import site.teamo.biu.net.common.exception.BiuNetBusinessException;
import site.teamo.biu.net.common.web.configuration.PassportConfiguration;
import site.teamo.biu.net.common.web.constant.ResponseCode;
import site.teamo.biu.net.common.web.mapper.SystemConfigMapper;
import site.teamo.biu.net.common.web.service.PassportService;

import java.util.Optional;

/**
 * @author haocongshun
 * @date 2023/03/06 11:14:36
 */
@Service
public class PassportServiceImpl implements PassportService {

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Override
    public boolean verifyPassword(String password) {
        return Optional.ofNullable(systemConfigMapper.selectById(PassportConfiguration.PASSWORD.id()))
                .map(p -> StrUtil.equals(DigestUtil.md5Hex(password), p.getContent()))
                .orElse(false);
    }

    @Override
    public boolean changePassword(String oldPassword, String newPassword) {
        if (this.verifyPassword(oldPassword)) {
            systemConfigMapper.updateById(PassportConfiguration.PASSWORD.toSystemConfigDO(DigestUtil.md5Hex(newPassword)));
            return true;
        }
        throw new BiuNetBusinessException(ResponseCode.BUSINESS_ERROR, "旧密码不正确");
    }
}
